package com.smxy.hunzi.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.smxy.hunzi.common.utils.Constant;
import com.smxy.hunzi.common.utils.R;
import com.smxy.hunzi.gateway.utils.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @title: AuthorizeFilter
 * @projectName: xm
 * @description: TODO
 * @author: Zack_Tzh
 * @date: 2019/12/10  14:46
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private  static List<String> jwtExcludePath;
    static {
        jwtExcludePath = new ArrayList<>();
//        jwtExcludePath.add("/user/userinfo/login");
//        jwtExcludePath.add("/user/userinfo/list");
//        jwtExcludePath.add("/user/userinfo/update");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if(true)
            return chain.filter(exchange);
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        R r = new R();
        //2. 则获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 如果是登录请求则放行
        if (jwtExcludePath.contains(request.getURI().getPath())) {
            return chain.filter(exchange);
        }
        //4. 获取请求头
        HttpHeaders headers = request.getHeaders();
        //5. 请求头中获取令牌
        String token = headers.getFirst("token");
        //6. 判断请求头中是否有令牌
        if (!StringUtils.isEmpty(token)) {
            r.put("code", Constant.ResponseCode.NOT_TOKEN.getCode());
            r.put("msg",Constant.ResponseCode.NOT_TOKEN.getMsg());
            JSONObject message = new JSONObject(r);
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        //9. 如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            r.put("code", Constant.ResponseCode.TOKEM_INVALID.getCode());
            r.put("msg",Constant.ResponseCode.TOKEM_INVALID.getMsg());
            JSONObject message = new JSONObject(r);
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        //12. 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}